<?php
/**
 * Created by PhpStorm.
 * User: mars
 * Date: 2019/2/4
 * Time: 2:21 AM
 */

namespace api\models;

use common\helpers\Util;
use common\models\Goods;
use phpDocumentor\Reflection\Types\Integer;
use yii\web\ServerErrorHttpException;

/**
 * Class PartTimeJob
 * @package api\models\
 * @property bool $publish
 */
class PartTimeJob extends \common\models\PartTimeJob
{

    private $_publish;
    private $order_id;

    public function fields()
    {
        return [
            'id',
            'uid',
            'personal_cer'   => function ($model) {
                /**
                 * @var Mission $model
                 */
                return $model->u->getPersonCer();
            },
            'business_cer'   => function ($model) {
                /**
                 * @var Mission $model
                 */
                return $model->u->getBusinessCer();
            },
            'type',
            'status',
            'is_sign_up'     => function ($model) {
                /**
                 * @var PartTimeJob $model
                 */
                return $model->isSignUp();
            },
            'hide',
            'pay_needed',
            'order_id'       => function ($model) {
                return $model->order_id;
            },
            'title',
            'content',
            'contact_name',
            'contact_phone',
            'color',
            'latitude',
            'longitude',
            'ad_code',
            'location'       => function ($model) {
                return Util::getLocationByAdCode($model->ad_code);
            },
            'people_num',
            'now_people_num' => function ($model) {
                $num = JobRecord::find()->where(['jid' => $model->id])->count();

                return $model->people_num - $num > 0 ? $model->people_num - $num : 0;
            },
            'sign_end'       => function ($model) {
                return \Yii::$app->formatter->asDate($model->sign_end);
            },
            'start_at'       => function ($model) {
                return \Yii::$app->formatter->asDate($model->start_at);
            },
            'end_at'         => function ($model) {
                return \Yii::$app->formatter->asDate($model->end_at);
            },
            'work_start',
            'work_end',
            'salary',
            'salary_type',
            'job_type',
            'gender_needed',
            'pay_type',
            'created_at'     => function ($model) {
                return \Yii::$app->formatter->asDatetime($model->created_at);
            },

        ];
    }

    public function rules()
    {
        return [
//            [['uid', 'type'], 'required'],
//            [['pay_needed'], 'required'],
            [
                [
//                    'uid',
//                    'type',
                    'status',
                    'forbidden',
                    'pay_needed',
                    'created_at',
                    'updated_at',
                    'job_type',
                    'gender_needed',
                    'salary',
                    'salary_type',
                    'pay_type',
                    'people_num',
                    'good_id',
                    'hide',
                ],
                'integer'
            ],
            [
                [
                    'content',
                    'sign_end',
                    'start_at',
                    'end_at',
                ],
                'string'
            ],
            [
                [
                    'title',
                    'contact_name',
                    'contact_phone',
                    'color',
                    'latitude',
                    'longitude',
                    'ad_code',
                ],
                'string',
                'max' => 255
            ],
            [
                ['uid'],
                'exist',
                'skipOnError'     => true,
                'targetClass'     => User::className(),
                'targetAttribute' => ['uid' => 'id']
            ],
            [['work_start', 'work_end'], 'safe'],
            ['end_at', 'validateEndTime'],
            ['work_end', 'validateWorkTime'],
        ];
    }


    public function validateEndTime($attribute, $params)
    {
        if ( ! $this->hasErrors()) {
            if ($this->start_at > $this->end_at) {
                $this->addError($attribute, '结束时间不能早于开始时间');
            }
        }
    }

    public function validateWorkTime($attribute, $params)
    {
        if ( ! $this->hasErrors()) {
            if (strtotime($this->work_start) > strtotime($this->work_end)) {
                $this->addError($attribute, '下班时间不能早于上班时间');
            }
        }
    }

    /**
     * 厨初始化订单
     */
    public function generateOrder($uid)
    {
        $order          = new Order();
        $order->status  = Order::STATUS_NOT_PAY;
        $order->number  = 1;
        $order->type    = Order::TYPE_PART_TIME_POST;
        $order->good_id = $this->good_id;
        $order->uid     = $uid;
        if ($order->save()) {
            return $order->order_id;
        } else {
            throwException(new ServerErrorHttpException());
        }
    }

    /**
     *
     */
    public function initPost()
    {

    }

    /**
     *
     */
    public function post()
    {

    }

    //TODO:重构，将乱七八糟的操作分离  发布、表单生成、初始化
    public function beforeSave($insert)
    {
        $this->forbidden = self::ACCESS;
        if ($insert) {
            $this->view_num   = 5;
            $this->hide       = self::ACCESS;
            $this->created_at = $this->updated_at = time();
            if (isset($this->good_id)) {
                $good = Good::findOne($this->good_id);
                //判断是否为会员
                if (VipAssignment::useRight(\Yii::$app->getUser()->id, "part_time_post")) {
                    $this->pay_needed = self::PAY_NOT_NEEDED;
                    $this->status     = self::NOT_PAY_STATUS;
                    $this->forbidden  = self::ACCESS;
                    $this->color      = $good->color;
                } else {
                    //需要支付,不是vip的情况
                    $this->pay_needed = self::PAY_NEEDED;
                    $this->status     = self::NOT_PAY_STATUS;
                    $this->forbidden  = self::FORBIDDEN;
                    $this->color      = $good->color;
                    //生成订单
                    $this->order_id = $this->generateOrder(\Yii::$app->getUser()->id);

                }
            } else {
                $this->pay_needed = self::PAY_NOT_NEEDED;
                $this->status     = self::NOT_PAY_STATUS;
            }
        } else {
            $this->created_at = time();
        }

        $this->start_at    = strtotime(date("Y-m-d", $this->start_at));
        $this->end_at      = strtotime(date("Y-m-d", $this->end_at));
        $this->uid         = \Yii::$app->getUser()->id;
        $this->type        = self::PARTTIME_TYPE;
        $this->salary_type = JobInfo::SALARY_TYPE_DAY;

        return parent::beforeSave($insert);
    }


    //TODO: 重构
    public function afterSave($insert, $changedAttributes)
    {

        $info = new JobInfo();
//        var_dump($info);
        if ($insert) {
            $info->jid = $this->id;
            if ( ! empty($this->order_id)) {
                $order         = Order::findOne(['order_id' => $this->order_id]);
                $order->job_id = $this->id;
                $order->save(false);
            }
        } else {
            $info = JobInfo::findOne(['jid' => $this->id]);
            if (empty($info)) {
                $info      = new JobInfo();
                $info->jid = $this->id;
            }
        }

        $info->job_type = empty($this->job_type) ? 1 : $this->job_type;
        if (isset($this->color)) {
            $info->color = $this->color;
        }
        $info->latitude      = $this->latitude;
        $info->longitude     = $this->longitude;
        $info->ad_code       = $this->ad_code;
        $info->gender_needed = $this->gender_needed;
        $info->sign_end      = $this->sign_end;
        $info->start_at      = $this->start_at;
        $info->end_at        = $this->end_at;
        $info->work_end      = $this->work_end;
        $info->work_start    = $this->work_start;
        $info->salary        = $this->salary;
        $info->people_num    = $this->people_num;
        if (isset($this->salary_type)) {
            $info->salary_type = $this->salary_type;
        }
        $info->pay_typed = $this->pay_type;
        $info->good_id   = $this->good_id;
        $info->save(false);
        parent::afterSave($insert, $changedAttributes);
    }

    //判断是否发布
    public function getPublish()
    {
        if (
            (($this->pay_needed == self::PAY_NEEDED && $this->status == self::PAY_STATUS) || $this->pay_needed == self::PAY_NOT_NEEDED)
            && $this->forbidden == self::ACCESS
            && $this->hide == self::ACCESS) {
            return true;
        }

        return false;
    }

    public function afterFind()
    {
//        $this->created_at = date('Y-m-d H:i:s', $this->created_at);
//        $this->updated_at = date('Y-m-d H:i:s', $this->updated_at);
        parent::afterFind();
    }

    public function isSignUp()
    {
        if (JobRecord::findOne(['jid' => $this->id, 'uid' => \Yii::$app->getUser()->id])) {
            return true;
        }

        return false;
    }

    public static function orderSmsNotice()
    {

        return false;
    }


}